package com.qf.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 千锋健哥
 */
public class AuthFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("========初始化过滤器2, init方法执行========");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("======过滤器2执行业务方法===============");
        //1. 从请求中获取会话session对象
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        HttpSession session = request.getSession();

        //获取用户的访问路径, 如果是验证码路径放行, 如果是登录请求路径放行
        String uri = request.getRequestURI();
        if (uri.contains("/createCode")
                || uri.contains("/login")
                || uri.contains("/login.html")) {
            //放行
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        //2. 从session对象中获取当前登录用户的用户名
        String userName = (String)session.getAttribute("token");
        //3. 判断用户名是否为空, 如果为空说明没登录过. 跳转到登录页面重新登录
        if (userName == null) {
            response.sendRedirect(request.getServletContext().getContextPath() + "/login.html");
        } else {
            //4. 如果用户名不为空, 那么当前过滤器请求放行
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {
        System.out.println("========初始化过滤器2, destroy方法执行========");
    }

}
